#include "view.h"
#include <QMouseEvent>
#include <QKeyEvent>
View::View()
{
    init();
}

void View::init()
{
    this->setMouseTracking(true);
    // 设置刷新模式为全刷新
    this->setViewportUpdateMode(QGraphicsView::FullViewportUpdate);

    // 设置渲染模式，抗锯齿全开
    this->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    // 设置抓取模式为框选模式
    this->setDragMode(DragMode::RubberBandDrag);

    // 隐藏滚动条
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);
}



// 滚轮事件放大缩小
void View::wheelEvent(QWheelEvent *event)
{
    // ctrl 一起按下时触发
    if(event->modifiers() & Qt::ControlModifier){
        QTransform matrix;
        qreal scale = 1;
        if(event->angleDelta().y() > 0){
            scale = 1.2;
        }else if (event->angleDelta().y() < 0){
            scale = 0.8;
        }
        event->accept();
        matrix.scale(scale, scale);
        this->setTransform(this->transform() * matrix);
    }else {
        QGraphicsView::wheelEvent(event);
    }
}


// 鼠标点击事件
void View::mousePressEvent(QMouseEvent *event)
{
//    // 中键点击按压时，模拟左键按压
//    if(event->button() == Qt::MiddleButton){
//        // 设置可拖动
//        this->setDragMode(DragMode::ScrollHandDrag);
//        this->setInteractive(false); //默认是true
//        auto event0 = new QMouseEvent(QEvent::MouseButtonPress, event->pos(), Qt::LeftButton, event->buttons(), event->modifiers());
//        QGraphicsView::mousePressEvent(event0);
//    }else {
//        QGraphicsView::mousePressEvent(event);
//    }

    QGraphicsView::mousePressEvent(event);
}

void View::mouseMoveEvent(QMouseEvent *event)
{
    QGraphicsView::mouseMoveEvent(event);
}

void View::keyPressEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key::Key_Space) {
        setInteractive(false);
        setDragMode(DragMode::ScrollHandDrag);
    }
    QGraphicsView::keyPressEvent(event);
}

void View::keyReleaseEvent(QKeyEvent *event)
{
    if(event->key() == Qt::Key::Key_Space) {
        setInteractive(true);
        setDragMode(DragMode::RubberBandDrag);
    }
    QGraphicsView::keyReleaseEvent(event);
}


void View::mouseReleaseEvent(QMouseEvent *event)
{
//    if(event->button() == Qt::MiddleButton){
//        this->setDragMode(DragMode::RubberBandDrag);
//        this->setInteractive(true); //默认是true
//        auto event0 = new QMouseEvent(QEvent::MouseButtonRelease, event->pos(), Qt::LeftButton, event->buttons(), event->modifiers());
//        QGraphicsView::mouseReleaseEvent(event0);
//    }else {
//        QGraphicsView::mouseReleaseEvent(event);
//    }
    QGraphicsView::mouseReleaseEvent(event);
}


